package com.mobisys.live.controller;

import com.mobisys.live.bean.channel.GetAllLiveList;
import com.mobisys.live.bean.im_group.NewGroupBean;
import com.mobisys.live.bean.live.CreateNewLive;
import com.mobisys.live.bean.live.GetLiveInfo;
import com.mobisys.live.bean.live.Guest;
import com.mobisys.live.bean.live.Schedule;
import com.mobisys.live.dao.mapper.*;
import com.mobisys.live.dao.model.*;
import com.mobisys.live.im.TimRestApi;
import com.mobisys.live.im.TlsSignature;
import com.mobisys.live.response.Response;
import com.mobisys.live.response.channel.LiveResponseBody;
import com.mobisys.live.response.live.LiveInfoResponseBody;
import com.mobisys.live.response.live.SimpleLiveInfoResponseBody;
import com.mobisys.live.response.tim.CreateGroupResponse;
import com.mobisys.live.util.LiveUtil;
import com.mobisys.live.util.UUIDUtil;
import com.mobisys.live.util.ValidationUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import java.util.*;

import static com.mobisys.live.config.ResponseCode.*;

/**
 * Created by zhuo on 2018-01-16.
 */
@RestController
public class LiveController {
    private Logger logger= LogManager.getLogger(LiveController.class.getName());

    @Autowired
    private LiveMapper liveMapper;

    @Autowired
    private GroupInfoMapper groupInfoMapper;

    @Autowired
    private PictureMapper pictureMapper;

    @Autowired
    private GuestMapper guestMapper;

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Autowired
    private ChannelMapper channelMapper;

    /**
     * 创建直播
     * @param createNewLive
     * @param bindingResult
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/live/createNewLive",method = RequestMethod.POST)
    public Response createNewLive(@RequestBody CreateNewLive createNewLive, BindingResult bindingResult,HttpServletRequest httpServletRequest){

        Response response=new Response();

        if(bindingResult.hasErrors()){
            response.setRetureValue(INPUT_IS_INVALID);
            response.setRetureMsg(MSG_INPUT_IS_INVALID+ ValidationUtil.getValidationInfo(bindingResult));
            return response;
        }


        String userId=createNewLive.getUserId();
        String channelId=createNewLive.getChannelId();


        List<LiveWithBLOBs> liveList=liveMapper.selectLiveListByChannelId(channelId);
        if(liveList!=null&&liveList.size()>1){
            response.setRetureValue(ONE_CHANNEL_CAN_ONLY_HAVE_ONE_LIVE);
            response.setRetureMsg(MSG_ONE_CHANNEL_CAN_ONLY_HAVE_ONE_LIVE);
            return response;
        }

        Channel channel=channelMapper.selectByPrimaryKey(channelId);
        String channelNum=channel.getChannelNumber();


        //创建一个聊天室群组，返回群组id
        String groupId="";
        NewGroupBean newGroupBean=new NewGroupBean();
        newGroupBean.setOwner_Account(userId);
        newGroupBean.setName(channelNum);//群组名称
        newGroupBean.setMaxMemberCount(500);
        //String userSig= TlsSignature.genTLSSig(userId);//登录即时通信需要使用的userSig
        CreateGroupResponse createGroupResponse= TimRestApi.groupCreateGroup(newGroupBean);
        if(createGroupResponse.getErrorCode()==0){
            groupId=createGroupResponse.getGroupId();
        }else {
            response.setRetureValue(IM_SDK_CREATE_GROUP_ERROR);
            response.setRetureMsg(MSG_IM_SDK_CREATE_GROUP_ERROR);
            return response;
        }


        //向群组表插入信息
        GroupInfo groupInfo=new GroupInfo();
        groupInfo.setGroupId(groupId);
        groupInfo.setHeadPictureId("");
        groupInfo.setUserId(createNewLive.getUserId());
        groupInfo.setId(UUIDUtil.getUUID());

        LiveWithBLOBs live=new LiveWithBLOBs();
        String liveId= UUIDUtil.getUUID();

        //向腾讯云请求直播相关的信息
        String pushUrl= LiveUtil.getStreamUrl(liveId);
        String hlsPlayUrl=LiveUtil.getHLSPlayUrl(liveId);
        String flvPlayUrl=LiveUtil.getFLVPlayUrl(liveId);
        String rtmpPlayUrl=LiveUtil.getRTMPPlayUrl(liveId);





        live.setId(liveId);
        live.setUserId(userId);
        live.setChannelid(createNewLive.getChannelId());
        live.setGroupid(groupId);

        live.setTitle(createNewLive.getLiveName());
        live.setType(createNewLive.getType());
        live.setLocation(createNewLive.getLocation());
        //图片信息
        Picture picture=new Picture();
        String pictureId=UUIDUtil.getUUID();
        picture.setId(pictureId);
        picture.setOriginal(createNewLive.getCoverPicture());
        if(pictureMapper.insertSelective(picture)>0){
            live.setCoverPictureId(pictureId);
        }else {
            live.setCoverPictureId("");
        }

        live.setCoverPictureId(pictureId);
        live.setCreateTime(new Date(System.currentTimeMillis()));
        live.setEndTime(new Date(System.currentTimeMillis()));
        live.setRtmpPlayUrl(rtmpPlayUrl);
        live.setHlsPlayUrl(hlsPlayUrl);
        live.setFlvPlayUrl(flvPlayUrl);
        live.setPushUrl(pushUrl);
        live.setTag("");

        //加入嘉宾及议程信息
        List<Guest> guestList=createNewLive.getGuestList();
        List<Schedule> scheduleList=createNewLive.getScheduleList();
        String guestIdStr="";
        String scheduleIdStr="";
        if(guestList!=null){
            for (int i = 0; i < guestList.size(); i++) {
                Guest guestInfo=guestList.get(i);
                com.mobisys.live.dao.model.Guest guest=new com.mobisys.live.dao.model.Guest();
                guest.setName(guestInfo.getName());
                guest.setEmployer(guestInfo.getEmployer());
                guest.setIntroduction(guestInfo.getIntroduction());

                guestMapper.insertSelective(guest);
            }
            live.setGuest(guestIdStr);//插入嘉宾信息id串
        }

        if(scheduleList!=null){
            for (int i = 0; i < scheduleList.size(); i++) {
                Schedule scheduleInfo=scheduleList.get(i);

                com.mobisys.live.dao.model.Schedule schedule=new com.mobisys.live.dao.model.Schedule();
                schedule.setTitle(scheduleInfo.getTitle());
                schedule.setContent(scheduleInfo.getContent());
                schedule.setHosting(scheduleInfo.getHosting());
                //schedule.setStartTime();
                //schedule.setEndTime();

                scheduleMapper.insertSelective(schedule);

            }

            live.setSchduled(scheduleIdStr);
        }

        SimpleLiveInfoResponseBody responseBody=new SimpleLiveInfoResponseBody();


        if(liveMapper.insertSelective(live)>0){

            response.setRetureValue(SUCCESS);
            response.setRetureMsg(MSG_SUCCESS);
            responseBody.setLiveId(liveId);
            responseBody.setPushUrl(pushUrl);
            responseBody.setPlayUrl(hlsPlayUrl);
            response.setRetureData(responseBody);
            return response;
        }else {

            response.setRetureValue(DATABASE_ERROR);
            response.setRetureMsg(MSG_DATABASE_ERROR);
            return response;

        }

    }

    /**
     * 获取直播信息
     * @param getLiveInfo
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/live/getLiveInfo",method = RequestMethod.POST)
    public Response getLiveInfo(@RequestBody GetLiveInfo getLiveInfo,BindingResult bindingResult, HttpServletRequest httpServletRequest){


        Response response=new Response<LiveInfoResponseBody>();

        if(bindingResult.hasErrors()){
            response.setRetureValue(INPUT_IS_INVALID);
            response.setRetureMsg(MSG_INPUT_IS_INVALID+ ValidationUtil.getValidationInfo(bindingResult));
            return response;
        }

        LiveWithBLOBs liveWithBLOBs=liveMapper.selectByPrimaryKey(getLiveInfo.getLiveId());
        if(liveWithBLOBs==null){
            response.setRetureValue(DATABASE_ERROR);
            response.setRetureMsg(MSG_DATABASE_ERROR);
            return response;
        }else {
            LiveInfoResponseBody responseBody=new LiveInfoResponseBody();
            responseBody.setUserId(liveWithBLOBs.getUserId());
            responseBody.setChannelId(liveWithBLOBs.getUserId());
            responseBody.setTitle(liveWithBLOBs.getTitle());
            responseBody.setGroupId(liveWithBLOBs.getGroupid());

            //获取图片的地址
            responseBody.setCoverPicture(liveWithBLOBs.getCoverPictureId());
            responseBody.setStartTime(liveWithBLOBs.getCreateTime());
            responseBody.setEndTime(liveWithBLOBs.getEndTime());

            responseBody.setLocation(liveWithBLOBs.getLocation());
            responseBody.setIntroduction(liveWithBLOBs.getLocation());
            responseBody.setType(liveWithBLOBs.getType());

            //获取推流地址、观看地址
            responseBody.setPushUrl(liveWithBLOBs.getPushUrl());
            responseBody.setPlayUrl(liveWithBLOBs.getHlsPlayUrl());
            responseBody.setHlsPlayUrl(liveWithBLOBs.getHlsPlayUrl());
            responseBody.setFlvPlayUrl(liveWithBLOBs.getFlvPlayUrl());
            responseBody.setRtmpPlayUrl(liveWithBLOBs.getRtmpPlayUrl());



            //获取嘉宾
            List<Guest> guestList=new ArrayList<>();

            responseBody.setGuestList(guestList);

            //获取议程
            List<Schedule> scheduleList=new LinkedList<>();

            responseBody.setSchduledList(scheduleList);


            response.setRetureValue(SUCCESS);
            response.setRetureMsg(MSG_SUCCESS);
            response.setRetureData(responseBody);

            return response;
        }



    }


    /**
     * 获取频道中的直播，频道默认只有一个直播
     * @param getAllLiveList
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/live/getLiveInChannel",method = RequestMethod.POST)
    public Response getLive(@Validated @RequestBody GetAllLiveList getAllLiveList, BindingResult bindingResult, HttpServletRequest httpServletRequest){
        Response response=new Response<List<LiveResponseBody>>();

        //检查输入是否合法
        //检查输入的合法性
        if(bindingResult.hasErrors()){
            response.setRetureValue(INPUT_IS_INVALID);
            response.setRetureMsg(MSG_INPUT_IS_INVALID);

            return response;
        }

        //取出一个频道中的直播
        List<LiveWithBLOBs> liveList=liveMapper.selectLiveListByChannelId(getAllLiveList.getChannelId());
        if(liveList==null){
            response.setRetureValue(DATABASE_ERROR);
            response.setRetureMsg(MSG_DATABASE_ERROR);
            return response;
        }else {
            response.setRetureValue(SUCCESS);
            response.setRetureMsg(MSG_SUCCESS);
            List<LiveResponseBody> list=new ArrayList<>();

            for (int i = 0; i < liveList.size(); i++) {
                LiveResponseBody liveResponseBody=new LiveResponseBody();
                LiveWithBLOBs live=liveList.get(i);
                liveResponseBody.setLiveId(live.getId());
                liveResponseBody.setLiveName(live.getTitle());
                liveResponseBody.setLocation(live.getLocation());
                liveResponseBody.setStartTime(live.getCreateTime().toString());
                liveResponseBody.setEndTime(live.getEndTime().toString());
                liveResponseBody.setGroupId(live.getGroupid());
                liveResponseBody.setRtmpPlayUrl(live.getRtmpPlayUrl());
                liveResponseBody.setHlsPlayUrl(live.getHlsPlayUrl());
                liveResponseBody.setFlvPlayUrl(live.getFlvPlayUrl());
                liveResponseBody.setPushUrl(live.getPushUrl());


                list.add(liveResponseBody);
            }

            response.setRetureData(list);

            return response;
        }


    }


    /*@RequestMapping(value = "/live/test",method = RequestMethod.GET)
    public Response liveTest(HttpServletRequest httpServletRequest){


        Response response=new Response();
        response.setRetureValue(0);
        response.setRetureMsg("test successful");
        logger.debug(response.toString());
        return response;

    }*/
}
